using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    public class GetCustomerByIdCommandHandler : IRequestHandler<GetCustomerByIdCommands, APIResult<Customer>>
    {
        private readonly IBaseRepository<Customer> customerRep;

        public GetCustomerByIdCommandHandler(IBaseRepository<Customer> customerRep)
        {
            this.customerRep = customerRep;
        }

        public Task<APIResult<Customer>> Handle(GetCustomerByIdCommands request, CancellationToken cancellationToken)
        {
            if (request == null || request.CustomerId <= 0)
            {
                return Task.FromResult(new APIResult<Customer>
                {
                    Code = APIEnums.Fail,
                    Msg = "参数无效：CustomerId",
                    Data = null
                });
            }

            try
            {
                var entity = customerRep.QueryFirstOrDefault<Customer>(
                    "SELECT * FROM Customer WHERE Id = @Id AND IsDeleted = false",
                    new { Id = request.CustomerId });

                if (entity == null)
                {
                    return Task.FromResult(new APIResult<Customer>
                    {
                        Code = APIEnums.Fail,
                        Msg = "客户不存在或已删除",
                        Data = null
                    });
                }

                return Task.FromResult(new APIResult<Customer>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = entity
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<Customer>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = null
                });
            }
        }
    }
}
